package com.cater.talents.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Company;
import com.cater.sys.entity.School;
import com.cater.sys.service.impl.CompanyServiceImpl;
import com.cater.sys.service.impl.SchoolServiceImpl;
import com.cater.talents.entity.DataCollection;
import com.cater.talents.entity.EduExperience;
import com.cater.talents.entity.Resume;
import com.cater.talents.entity.WorkExperience;
import com.cater.talents.service.DataCollectionServiceImpl;
import com.cater.talents.service.EduExperienceServiceImpl;
import com.cater.talents.service.ResumeServiceImpl;
import com.cater.talents.service.WorkExperienceServiceImpl;

/**
 * 描述：数据采集控制层
 * 
 * @author yong
 * @date 2018/10/14
 */
@Controller
@RequestMapping("/dataCollection")
public class DataCollectionController {

	@Autowired
	private DataCollectionServiceImpl service;
	@Autowired
	private ResumeServiceImpl resumeService;
	@Autowired
	private WorkExperienceServiceImpl workExperienceService;
	@Autowired
	private CompanyServiceImpl companyService;// 公司
	@Autowired
	private EduExperienceServiceImpl eduExperienceService;
	@Autowired
	private SchoolServiceImpl schoolService;// 学校

	/**
	 * @数据采集管理列表视图
	 * @return
	 */
	@RequestMapping("/list")
	public String list() {
		return "talents/dataCollection/list";
	}

	/**
	 * @数据采集管理数据分页
	 * @param query
	 * @param request
	 * @return
	 */
	@RequestMapping("listData")
	@ResponseBody
	@SystemControllerLog(description = "查询数据采集分页数据")
	public PageResult<DataCollection> listData(CommonQuery query, HttpServletRequest request) {
		PageResult<DataCollection> result = service.findPageResult(query);
		return result;
	}

	/**
	 * 添加视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("dataCollection:add")
	public String addView() {
		return "talents/dataCollection/add";
	}

	/**
	 * 添加操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("dataCollection:add")
	@ResponseBody
	@SystemControllerLog(description = "添加数据采集")
	public JSONObject add(DataCollection t, CommonQuery query) {
		JSONObject json = new JSONObject();
		String id = service.saves(t);
		if (StringUtils.isNotBlank(id)) {
			json.put("code", 200);
			json.put("message", "success");
		} else {
			json.put("code", 999);
			json.put("message", "fail");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("dataCollection:edit")
	public String editView(String id, Model model, CommonQuery query) {
		DataCollection t = service.getById(id);
		List<Map<String, String>> workList = new ArrayList<Map<String, String>>();
		String workDates[] = t.getWorkDate().split("###");
		String workCompanys[] = t.getWorkCompany().split("###");
		String workJobs[] = t.getWorkJob().split("###");
		String workSalarys[] = t.getSalary().split("###");
		String workDetails[] = t.getWorkDetail().split("###");
		Integer type = t.getType();
		if (type == 2) {
			t.setPhone(null);
			t.setEmail(null);
			Map<String, String> workMap = new HashMap<String, String>();
			workMap.put("work_start_date", null);
			workMap.put("work_end_date", null);
			workMap.put("work_company", null);
			workMap.put("work_job", null);
			workMap.put("work_salary", null);
			workMap.put("work_detail", null);
			workList.add(workMap);
		} else {
			for (int i = 0; i < workDates.length; i++) {
				Map<String, String> workMap = new HashMap<String, String>();
				String tWorkDates[] = workDates[i].split("—");
				workMap.put("work_start_date", tWorkDates[0]);
				workMap.put("work_end_date", tWorkDates[1]);
				if (i < workCompanys.length) {
					workMap.put("work_company", workCompanys[i]);
				} else {
					workMap.put("work_company", null);
				}
				if (i < workJobs.length) {
					workMap.put("work_job", workJobs[i]);
				} else {
					workMap.put("work_job", null);
				}
				if (i < workSalarys.length) {
					workMap.put("work_salary", workSalarys[i]);
				} else {
					workMap.put("work_salary", null);
				}
				if (i < workDetails.length) {
					workMap.put("work_detail", workDetails[i]);
				} else {
					workMap.put("work_detail", null);
				}
				workList.add(workMap);
			}
		}
		model.addAttribute("dataCollection", t);
		model.addAttribute("workList", workList);
		model.addAttribute("work_num", workList.size());
		List<Map<String, String>> eduList = new ArrayList<Map<String, String>>();
		String eduDates[] = t.getEduDate().split("###");
		String eduNames[] = t.getEduName().split("###");
		String eduPros[] = t.getEduPro().split("###");
		String educations[] = t.getEducation().split("###");
		for (int k = 0; k < eduDates.length; k++) {
			Map<String, String> edukMap = new HashMap<String, String>();
			String tEduDates[] = eduDates[k].split("-");
			edukMap.put("edu_start_date", tEduDates[0]);
			edukMap.put("edu_end_date", tEduDates[1]);
			edukMap.put("edu_date", eduDates[k]);
			if (k < eduNames.length) {
				edukMap.put("edu_name", eduNames[k]);
			} else {
				edukMap.put("work_company", null);
			}
			if (k < eduPros.length) {
				edukMap.put("edu_pro", eduPros[k]);
			} else {
				edukMap.put("edu_pro", null);
			}
			if (k < educations.length) {
				edukMap.put("education", educations[k]);
			} else {
				edukMap.put("education", null);
			}
			eduList.add(edukMap);
		}
		model.addAttribute("eduList", eduList);
		model.addAttribute("edu_num", eduList.size());
		List<Map<String, String>> trainList = new ArrayList<Map<String, String>>();
		String trainNames[] = t.getTrainName().split("###");
		String trainPros[] = t.getTrainPro().split("###");
		String trainDates[] = t.getTrainDate().split("###");
		String trainDetails[] = t.getTrainDetail().split("###");
		if (type == 1) {
			for (int j = 0; j < trainDates.length; j++) {
				Map<String, String> trainkMap = new HashMap<String, String>();
				if (j < eduDates.length) {
					String tTrainDates[] = eduDates[j].split("-");
					trainkMap.put("train_start_date", tTrainDates[0]);
					trainkMap.put("train_end_date", tTrainDates[1]);
				} else {
					trainkMap.put("train_start_date", null);
					trainkMap.put("train_end_date", null);
				}
				if (j < trainNames.length) {
					trainkMap.put("train_name", trainNames[j]);
				} else {
					trainkMap.put("train_name", null);
				}
				if (j < eduNames.length) {
					trainkMap.put("train_pro", trainPros[j]);
				} else {
					trainkMap.put("train_pro", null);
				}
				if (j < trainDetails.length) {
					trainkMap.put("train_detail", trainDetails[j]);
				} else {
					trainkMap.put("train_detail", null);
				}
				trainList.add(trainkMap);
			}
		}
		model.addAttribute("train_num", trainList.size());
		model.addAttribute("trainList", trainList);
		if (t.getType() == 1) {
			model.addAttribute("type", 5);
		} else if (t.getType() == 2) {
			model.addAttribute("type", 4);
		} else {
			model.addAttribute("type", 1);
		}
		return "talents/dataCollection/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("dataCollection:edit")
	@ResponseBody
	@SystemControllerLog(description = "修改数据采集")
	public JSONObject update(String dataId, Resume resume, Integer worknum, Integer edunum, Integer trainnum,
			CommonQuery query, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			String talentid = resumeService.saves(resume);
			if (StringUtils.isNotEmpty(talentid)) {
				for (int i = 1; i < worknum + 1; i++) {
					String startDate = request.getParameter("startDate" + i);
					String endDate = request.getParameter("endDate" + i);
					// String companyId = request.getParameter("companyId" + i);
					String temp_companyName = request.getParameter("companyName" + i);
					String companyName = temp_companyName.replace("'", "");
					String position = request.getParameter("position" + i);
					String depId = request.getParameter("depId" + i);
					String report = request.getParameter("report" + i);
					String subordinateNum = request.getParameter("subordinateNum" + i);
					String responsibility = request.getParameter("responsibility" + i);
					String performance = request.getParameter("performance" + i);
					String project = request.getParameter("project" + i);
					String job = request.getParameter("job" + i);
					String workplace = request.getParameter("workplace" + i);
					String description = request.getParameter("description" + i);
					if (StringUtils.isNotEmpty(companyName)) {
						WorkExperience wExperience = new WorkExperience();
						Company company = new Company();
						query.setName(companyName);
						company = companyService.getByName(query);
						if (company != null) {
							company.setId(company.getId());
						} else {
							company = new Company();
							company.setName(companyName);
							String company_id = companyService.saves(company);
							company.setId(company_id);
						}
						wExperience.setCompany(company);
						wExperience.setCompanyName(companyName);
						wExperience.setTalentsId(talentid);
						wExperience.setStartDate(startDate);
						if (StringUtils.isNotEmpty(endDate)) {
							wExperience.setEndDate(endDate);
						} else {
							wExperience.setEndDate("至今");
						}
						wExperience.setPosition(position);
						wExperience.setDepId(depId);
						wExperience.setReport(report);
						if (StringUtils.isNotEmpty(subordinateNum)) {
							wExperience.setSubordinateNum(Integer.valueOf(subordinateNum));
						}
						wExperience.setResponsibility(responsibility);
						wExperience.setPerformance(performance);
						wExperience.setProject(project);
						wExperience.setJob(job);
						wExperience.setWorkplace(workplace);
						wExperience.setDescription(description);
						workExperienceService.saves(wExperience);
					}
				}
				for (int i = 1; i < edunum + 1; i++) {
					String startDate = request.getParameter("startDate" + i);
					String endDate = request.getParameter("endDate" + i);
					String temp_schoolName = request.getParameter("schoolName" + i);
					String schoolName = null;
					if (StringUtils.isNotEmpty(temp_schoolName)) {
						schoolName = temp_schoolName.replaceAll("'", "");
					}
					String profession = request.getParameter("profession" + i);
					String education = request.getParameter("education" + i);
					String unified = request.getParameter("unified" + i);
					EduExperience experience = new EduExperience();
					if (StringUtils.isNotEmpty(schoolName)) {
						School edu = new School();
						query.setName(schoolName);
						edu = schoolService.getByName(query);
						if (edu != null) {
							edu.setId(edu.getId());
						} else {
							edu = new School();
							edu.setName(schoolName);
							edu.setClassify("1");
							String edu_id = schoolService.saves(edu);
							edu.setId(edu_id);
						}
						experience.setSchool(edu);
						experience.setSchoolName(schoolName);
						experience.setType("1");
						experience.setTalentsId(talentid);
						experience.setStartDate(startDate);
						if (StringUtils.isNotEmpty(endDate)) {
							experience.setEndDate(endDate);
						} else {
							experience.setEndDate("至今");
						}
						experience.setProfession(profession);
						experience.setEducation(education);
						experience.setUnified(Integer.valueOf(unified));
						eduExperienceService.saves(experience);
					}
				}
				for (int i = 1; i < trainnum + 1; i++) {
					String startDate = request.getParameter("startDate" + i);
					String endDate = request.getParameter("endDate" + i);
					String temp_schoolName = request.getParameter("schoolName" + i);
					String schoolName = null;
					if (StringUtils.isNotEmpty(temp_schoolName)) {
						schoolName = temp_schoolName.replaceAll("'", "");
					}
					String course = request.getParameter("course" + i);
					String grade = request.getParameter("grade" + i);
					EduExperience experience = new EduExperience();
					if (StringUtils.isNotEmpty(schoolName)) {
						School edu = new School();
						query.setName(schoolName);
						edu = schoolService.getByName(query);
						if (edu != null) {
							edu.setId(edu.getId());
						} else {
							edu = new School();
							edu.setName(schoolName);
							edu.setClassify("2");
							String edu_id = schoolService.saves(edu);
							edu.setId(edu_id);
						}
						experience.setSchool(edu);
						experience.setSchoolName(schoolName);
						experience.setType("2");
						experience.setTalentsId(talentid);
						experience.setStartDate(startDate);
						experience.setEndDate(endDate);
						experience.setCourse(course);
						experience.setGrade(grade);
						eduExperienceService.saves(experience);
					}
				}
			}
			DataCollection dataCollection = service.getById(dataId);
			if (dataCollection != null) {
				/**
				 * 2为已采纳
				 */
				dataCollection.setIsAdopt("2");
				service.update(dataCollection);
			}
			json.put("code", 200);
			json.put("message", "采纳成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "采纳失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("dataCollection:delete")
	@SystemControllerLog(description = "删除数据采集")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			service.delete(id);
			json.put("code", 200);
			json.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	/**
	 * 查看视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "detailView")
	@RequiresPermissions("dataCollection:detail")
	public String detailView(String id, Model model, CommonQuery query) {
		DataCollection t = service.getById(id);
		model.addAttribute("dataCollection", t);
		return "talents/dataCollection/detail";
	}

}